package com.me.myFramework.myJedis;

import java.io.IOException;
import java.io.OutputStream;

/**
 * Redis 协议层：RESP
 * 假设 set("wukong", "2019")
 *  <blockquote>
 *      *3<p><p>
 *      $3<p>
 *      SET<p><p>
 *      $2<p>
 *      me<p><p>
 *      $4<p>
 *      2019<p>
 *  </blockquote>
 *
 * @author ME
 * @date   2019/3/5 15:47
 */
public class Protocol {

    public static final String DOLLAR_BYTE = "$";
    public static final String ARRAY_BYTE = "*";
    public static final String BALNK_BYTE = "\r\n";

    /**
     * 根据 RESP 协议拼装报文
     * @param out
     * @param commond
     * @param bytes
     */
    public static void sendCommond(OutputStream out, Commond commond, byte[]... bytes) {
        if (bytes.length == 0) {
            throw new IllegalArgumentException("bytes 至少为1个");
        }

        StringBuffer buffer = new StringBuffer();
        buffer.append(ARRAY_BYTE).append(bytes.length + 1).append(BALNK_BYTE);// *3
        buffer.append(DOLLAR_BYTE).append(commond.name().length()).append(BALNK_BYTE);// $3
        buffer.append(commond.name()).append(BALNK_BYTE);// SET
        for (byte[] arg : bytes) {
            buffer.append(DOLLAR_BYTE).append(arg.length).append(BALNK_BYTE);// $2
            buffer.append(new String(arg)).append(BALNK_BYTE);// me
        }
        try {
            out.write(buffer.toString().getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static enum Commond {
        SET,
        GET
    }

}
